import XLSX from 'xlsx';
import { importStore } from './api';
import { message } from '@/utils/util';

export default {
  name: 'import-store-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    topChannelList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      formValue: {},
      formRules: {
        topChannelCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.topChannelCode) {
                callback('顶级渠道不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        stores: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.channelStoreList) {
                callback('导入信息不能为空');
              } else {
                callback();
              }
            },
          },
        ],
      },
      formLabelWidth: '100px',
      resultVisible: false,
      tipData: [],
      importing: false,
    };
  },
  watch: {},
  methods: {
    async onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          try {
            this.importing = true;
            this.tipData = await importStore(this.formValue);
            if (this.tipData.length > 0) {
              this.resultVisible = true;
            }
            this.onClose();
            this.resetTable();
            message('提示', '导入成功', 'success');
          } catch (e) {
            message('错误', e.message, 'error');
          }
          this.importing = false;
        }
      });
    },
    resetTable() {
      this.$emit('resetTable');
    },
    onClose() {
      this.formValue = {};
      this.$refs.formRef.resetFields();
      this.$refs.upload.uploadFiles = [];
      this.$emit('close');
    },
    onChange(file) {
      const reader = new FileReader();
      reader.onload = e => {
        let data = e.target.result;
        const workbook = XLSX.read(data, { type: 'buffer' });
        const [sheetName] = workbook.SheetNames;
        const sheetInfo = workbook.Sheets[sheetName];
        if (
          !sheetInfo.A1 ||
          sheetInfo.A1.v !== '门店编码' ||
          !sheetInfo.B1 ||
          sheetInfo.B1.v !== '蜂窝编码' ||
          (!sheetInfo.C1 && sheetInfo.C1.v !== '店型') ||
          !sheetInfo.D1 ||
          sheetInfo.D1.v !== '城市运营经理'
        ) {
          message('提示', '模板格式错误', 'error');
          return;
        }
        const parsedSheetInfo = XLSX.utils.sheet_to_json(sheetInfo);
        this.formValue.channelStoreList = parsedSheetInfo.map((item, index) => ({
          rowNo: index + 1,
          storeCode: String(item['门店编码'] || ''),
          cellularCode: String(item['蜂窝编码'] || ''),
          storeLevel: String(item['店型'] || ''),
          operationManagerNumber: String(item['城市运营经理'] || ''),
        }));
        this.$refs.formRef.validateField('stores');
        message('提示', '文件上传成功', 'success');
      };
      reader.readAsArrayBuffer(file.raw);
    },
    onError() {
      message('错误', '文件上传失败', 'error');
    },
    //模板下载
    downImportTemplate() {
      window.location.href = './docs/门店批量导入信息模板.xlsx';
    },
    onCloseResultModal() {
      this.resultVisible = false;
    },
  },
  mounted() {},
};
